import java.util.Arrays;

public class Sort {

    public static void insertSort(int[]array){
        for (int i = 1; i <array.length ; i++) {
            int tmp=array[i];
            int j = i-1;
            for (; j >=0 ; j--) {
                if(array[j]>tmp){
                    array[j+1]=array[j];
                }else{
                    break;
                }
            }
            array[j+1]=tmp;
        }
    }


    public static void selectSort(int[]array){
        for (int i = 0; i < array.length; i++) {
            for (int j = i+1; j <array.length ; j++) {
                if(array[i]>array[j]){
                    int tmp=array[j];
                    array[j]=array[i];
                    array[i]=tmp;
                }
            }
        }
    }


    public static void bubbleSort(int[]array){
        for (int i = 0; i < array.length-1; i++) {
            boolean flg=false;
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j]>array[j+1]){
                    int tmp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=tmp;
                    flg=true;
                }
            }
            if(flg==false){
                break;
            }
        }
    }

    public static void heapSort(int[]array){
        createHeap(array);
        int end=array.length-1;
        while(end>0){
            int tmp=array[0];
            array[0]=array[end];
            array[end]=tmp;
            shiftDown(array,0,end);
            end--;
        }
    }

    public static void createHeap(int[]array){
        for (int parent = (array.length-1-1)/2; parent >=0 ; parent--) {
            shiftDown(array,parent,array.length);
        }
    }

    public static void shiftDown(int[]array,int parent,int len){
        int child=2*parent+1;
        while(child<len){
            if(child+1<len&&array[child+1]>array[child]){
                child++;
            }
            if(array[parent]<array[child]){
                int tmp=array[child];
                array[child]=array[parent];
                array[parent]=tmp;
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[]array={3,44,22,12,54,66,4,1};
        //insertSort(array);
        //selectSort(array);
        heapSort(array);
        //bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }
}
